<template>
  <div class="logistics-manager">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>物流管理</h2>
      <el-tag type="info">共 {{ total }} 条物流记录</el-tag>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="operation-area" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="物流状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="(label, value) in logisticsStatusMap" :key="value" :label="label" :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" plain type="primary" @click="handleSearch">查询</el-button>
          <el-button size="medium" plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 物流统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-position"></i></div>
                <div class="stat-title">运输中</div>
              </div>
              <div class="stat-value">{{ statistics.inTransitCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-circle-check"></i></div>
                <div class="stat-title">已签收</div>
              </div>
              <div class="stat-value">{{ statistics.deliveredCount || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-left">
                <div class="stat-icon"><i class="el-icon-warning"></i></div>
                <div class="stat-title">异常/退款</div>
              </div>
              <div class="stat-value">{{ (statistics.exceptionCount || 0) + (statistics.refundedCount || 0) }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 物流列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="logisticsList" border style="width: 100%">
        <el-table-column prop="orderId" label="订单号" width="120"></el-table-column>
        <el-table-column prop="companyName" label="快递公司" width="120"></el-table-column>
        <el-table-column prop="trackingNumber" label="快递单号" width="150"></el-table-column>
        <el-table-column label="收货信息" width="200">
          <template slot-scope="scope">
            <div>{{ scope.row.order?.recvAddress }}</div>
            <div>{{ scope.row.order?.recvPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="物流状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getLogisticsStatusType(scope.row.status)">
              {{ logisticsStatusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="expectedArrivalTime" label="预计到达时间" >
          <template slot-scope="scope">
            {{ formatTime(scope.row.expectedArrivalTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.size" @pagination="getList" />
    </el-card>

    <!-- 物流详情对话框 -->
    <el-dialog title="物流详情" :visible.sync="detailDialogVisible" width="600px">
      <div class="logistics-detail" v-if="currentLogistics">
        <div class="detail-section">
          <h4>物流信息</h4>
          <div class="logistics-card">
            <div class="detail-item">
              <span class="label">快递公司：</span>
              <span>{{ currentLogistics.companyName }}</span>
            </div>
            <div class="detail-item">
              <span class="label">快递单号：</span>
              <span class="tracking-number">
                {{ currentLogistics.trackingNumber }}
                <el-button 
                  type="text" 
                  size="mini" 
                  icon="el-icon-document-copy"
                  @click="copyTrackingNumber(currentLogistics.trackingNumber)">
                  复制
                </el-button>
              </span>
            </div>
            <div class="detail-item">
              <span class="label">物流状态：</span>
              <el-tag :type="getLogisticsStatusType(currentLogistics.status)">
                {{ logisticsStatusMap[currentLogistics.status] }}
              </el-tag>
            </div>
            <div class="detail-item">
              <span class="label">创建时间：</span>
              <span>{{ formatTime(currentLogistics.createdAt) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">更新时间：</span>
              <span>{{ formatTime(currentLogistics.updatedAt) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">预计到达：</span>
              <span>{{ formatTime(currentLogistics.expectedArrivalTime) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="logistics-card">
            <div class="detail-item">
              <span class="label">订单编号：</span>
              <span>{{ currentLogistics.orderId }}</span>
            </div>
            <div class="detail-item">
              <span class="label">订单状态：</span>
              <el-tag :type="getOrderStatusType(currentLogistics.order?.status)">
                {{ orderStatusMap[currentLogistics.order?.status] }}
              </el-tag>
            </div>
            <div class="detail-item" v-if="currentLogistics.order?.product">
              <span class="label">商品名称：</span>
              <span>{{ currentLogistics.order?.product?.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">订单金额：</span>
              <span class="price">¥{{ currentLogistics.order?.totalPrice }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>收货信息</h4>
          <div class="logistics-card">
            <div class="detail-item">
              <span class="label">收货人：</span>
              <span>{{ currentLogistics.order?.recvName}}</span>
            </div>
            <div class="detail-item">
              <span class="label">联系电话：</span>
              <span>{{ currentLogistics.order?.recvPhone }}</span>
            </div>
            <div class="detail-item">
              <span class="label">收货地址：</span>
              <span>{{ currentLogistics.order?.recvAddress }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Request from '@/utils/request'
import Pagination from '@/components/Pagination/index.vue'
import { formatTime } from '@/utils/time'

export default {
  name: 'LogisticsManager',
  inject: ['userInfo'],
  components: {
    Pagination
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        orderId: undefined,
        status: undefined
      },
      // 查询参数
      queryParams: {
        currentPage: 1,
        size: 10
      },
      // 物流列表
      logisticsList: [],
      // 总数
      total: 0,
      // 物流状态映射
      logisticsStatusMap: {
        1: '已发货',
        2: '运输中',
        3: '已签收',
        4: '异常',
        5: '已退款'
      },
      // 订单状态映射
      orderStatusMap: {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消',
        5: '已退款'
      
      },
      // 详情对话框
      detailDialogVisible: false,
      currentLogistics: null,
      // 添加统计数据
      statistics: {
        totalCount: 0,
        shippedCount: 0,
        inTransitCount: 0,
        deliveredCount: 0,
        exceptionCount: 0,
        refundedCount: 0,
        todayShippedCount: 0,
        weekShippedCount: 0,
        onTimeRate: 0,
        signRate: 0,
        avgDeliveryDays: 0
      }
    }
  },
  created() {
    this.getList()
    this.getStatistics()
  },
  methods: {
    // 获取物流列表
    async getList() {
      try {
        const merchantId = this.userInfo.role === 'MERCHANT' ? this.userInfo.id : undefined
        const params = {
          ...this.queryParams,
          ...this.searchForm,
          merchantId
        }
        const res = await Request.get('/logistics/page', { params })
        if (res.code === '0') {
          this.logisticsList = res.data.records || []
          this.total = res.data.total || 0
        } else {
          this.logisticsList = []
          this.total = 0
          this.$message.error(res.msg || '获取物流列表失败')
        }
      } catch (error) {
        this.logisticsList = []
        this.total = 0
        console.error('获取物流列表失败:', error)
        this.$message.error('获取物流列表失败')
      }
    },
    // 获取物流统计数据
    async getStatistics() {
      try {
        const merchantId = this.userInfo.role === 'MERCHANT' ? this.userInfo.id : undefined
        const params = { merchantId }
        const res = await Request.get('/logistics/statistics', { params })
        if (res.code === '0') {
          this.statistics = res.data
        } else {
          console.error('获取物流统计失败:', res.msg)
        }
      } catch (error) {
        console.error('获取物流统计失败:', error)
      }
    },
    // 搜索
    handleSearch() {
      this.queryParams.currentPage = 1
      this.getList()
      this.getStatistics()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        orderId: undefined,
        status: undefined
      }
      this.handleSearch()
    },
    // 获取物流状态类型
    getLogisticsStatusType(status) {
      const typeMap = {
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'danger',
        5: 'info'
      }
      return typeMap[status] || 'info'
    },
    // 获取订单状态类型
    getOrderStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'info',
        4: 'danger',
        5: 'warning',
        6: 'info',
        7: 'danger'
      }
      return typeMap[status] || 'info'
    },
    // 获取指定状态的物流数量
    getLogisticsCountByStatus(status) {
      if (!this.logisticsList) return 0
      return this.logisticsList.filter(item => item.status === status).length
    },
    // 查看详情
    handleDetail(logistics) {
      this.currentLogistics = logistics
      this.detailDialogVisible = true
    },
    // 格式化时间
    formatTime,
    // 复制快递单号
    copyTrackingNumber(trackingNumber) {
      const input = document.createElement('input')
      input.value = trackingNumber
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message.success('快递单号已复制')
    },
  }
}
</script>

<style scoped>
.logistics-manager {
  padding: 24px;
  background-color: #fff8f0;
  min-height: calc(100vh - 60px);
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 500;
  color: #E67E22;
  margin: 0;
  margin-right: 15px;
}

.operation-area {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.statistics-cards {
  margin-bottom: 24px;
  position: relative;
}

.stat-card {
  border-radius: 12px;
  transition: all 0.3s;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.stat-card:hover {
  box-shadow: 0 6px 20px rgba(243, 156, 18, 0.1);
  transform: none;
}

.stat-content {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(to right, #fff, #fff8e6);
  position: relative;
  overflow: hidden;
}

.stat-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(to bottom, #F39C12, rgba(243, 156, 18, 0.5));
}

.stat-left {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: flex-start;
}

.stat-icon {
  font-size: 26px;
  color: #F39C12;
  opacity: 0.8;
  text-align: center;
  background-color: rgba(243, 156, 18, 0.1);
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #E67E22;
  margin-right: 16px;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 美化表格 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: none;
}

:deep(.el-table th) {
  background-color: #fff4e0;
  font-weight: 500;
  color: #E67E22;
  padding: 14px 0;
}

:deep(.el-table td) {
  padding: 14px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fffbf5;
}

/* 美化对话框 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  padding: 24px;
  border-bottom: 1px solid #f5e8d3;
  margin: 0;
  background: #fff4e0;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 500;
  color: #E67E22;
}

:deep(.el-dialog__body) {
  padding: 32px 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f5e8d3;
  background: #faf7f0;
}

/* 美化表单 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #E67E22;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #f0d5b3;
  transition: all 0.3s;
  padding: 0 15px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-input__inner:focus) {
  border-color: #F39C12;
  box-shadow: 0 0 0 2px rgba(243, 156, 18, 0.2);
}

:deep(.el-select .el-input__inner:focus) {
  border-color: #F39C12;
}

:deep(.el-button--primary) {
  background-color: #F39C12;
  border-color: #F39C12;
  color: #fff;
}

:deep(.el-button--primary:hover) {
  background-color: #E67E22;
  border-color: #E67E22;
  color: #fff;
}

:deep(.el-button--text) {
  color: #F39C12;
}

:deep(.el-button) {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button:hover) {
  transform: none;
  box-shadow: none;
}

.detail-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5e8d3;
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.detail-section h4 {
  font-size: 16px;
  color: #E67E22;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.4;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  width: 100px;
  color: #909399;
}

/* 分页样式 */
:deep(.el-pagination) {
  padding: 20px 0;
  text-align: right;
}

:deep(.el-pagination button) {
  background: none;
}

:deep(.el-pagination .btn-next),
:deep(.el-pagination .btn-prev) {
  border: 1px solid #f0d5b3;
  border-radius: 8px;
}

:deep(.el-pager li) {
  border-radius: 8px;
  margin: 0 3px;
}

:deep(.el-pager li.active) {
  background-color: #F39C12;
  color: #fff;
}

:deep(.el-tag--info) {
  background-color: rgba(243, 156, 18, 0.1);
  border-color: rgba(243, 156, 18, 0.2);
  color: #F39C12;
}

.logistics-detail {
  padding: 0;
}

.logistics-card {
  background-color: #fff8f0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.tracking-number {
  display: flex;
  align-items: center;
}

.price {
  font-weight: 500;
  color: #f56c6c;
}
</style>